package com.ximu.coupon.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximu.car.entity.Car;
import com.ximu.common_utlis.jwt.JwtUtil;
import com.ximu.common_utlis.result.Result;
import com.ximu.coupon.entity.Coupon;
import com.ximu.coupon.mapper.CouponMapper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ximu
 * @since 2023-03-21
 */
@RestController
@RequestMapping("/coupon")
@Api(tags = "我的优惠券接口")
public class CouponController {

    @Autowired
    private CouponMapper couponMapper;

    @ApiOperation(value = "查询用户未使用的优惠券")
    @PostMapping("findAllCoupons")
    public Result findAllCoupons(@RequestHeader("Authorization") String token){
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();

            QueryWrapper<Coupon> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", Integer.parseInt(subject));
            queryWrapper.eq("is_exchange", 0);
            List<Coupon> coupons = couponMapper.selectList(queryWrapper);
            return Result.ok().data("coupons",coupons).message("成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("查询失败，检查是否登录");
    }

    @ApiOperation(value = "消费优惠券//尽量别直接调用，写支付接口会自动调用")
    @PostMapping("useCoupons")
    public Result useCoupons(@RequestHeader("Authorization") String token,int coupon_id){
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();

            QueryWrapper<Coupon> queryWrapper = new QueryWrapper();
            queryWrapper.eq("coupon_id", coupon_id);
            queryWrapper.eq("user_id", Integer.parseInt(subject));
            queryWrapper.eq("is_exchange", 0);
            Coupon coupons = couponMapper.selectOne(queryWrapper);

            if (Objects.nonNull(coupons)){
                coupons.setIsExchange(1);
                int rs = couponMapper.updateById(coupons);
                if (rs>0){
                    return Result.ok().data("coupons",coupons).message("使用成功");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("使用失败");
    }
}

